package com.tjec.project.system.service.impl;

import com.tjec.common.constant.Constants;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.web.domain.TreeSelect;
import com.tjec.framework.web.domain.TreeSelectAndChildrenNum;
import com.tjec.project.system.domain.BmsMdBusinessCategory;
import com.tjec.project.system.domain.BmsUserBusiness;
import com.tjec.project.system.domain.vo.BmsMdBusinessCategoryVO;
import com.tjec.project.system.mapper.BmsMdBusinessCategoryMapper;
import com.tjec.project.system.mapper.BmsUserBusinessMapper;
import com.tjec.project.system.service.IBmsMdBusinessCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务类别管理Service业务层处理
 *
 * @author tjec
 * @date 2020-04-03
 */
@Service
public class BmsMdBusinessCategoryServiceImpl implements IBmsMdBusinessCategoryService {
    @Autowired
    private BmsMdBusinessCategoryMapper bmsMdBusinessCategoryMapper;
    
    @Autowired
    private BmsUserBusinessMapper bmsUserBusinessMapper;

    /**
     * 查询业务类别管理
     *
     * @param id 业务类别管理ID
     * @return 业务类别管理
     */
    @Override
    public BmsMdBusinessCategory selectBmsMdBusinessCategoryById(String id) {
        return bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryById(id);
    }
    
    @Override
    public BmsMdBusinessCategory selectBmsMdBusinessCategoryByGuIdLimit(String guid) {
        return bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryByGuIdLimit(guid);
    }

    /**
     * 查询业务类别管理列表
     *
     * @param bmsMdBusinessCategory 业务类别管理
     * @return 业务类别管理
     */
    @Override
    public List<BmsMdBusinessCategory> selectBmsMdBusinessCategoryList(BmsMdBusinessCategory bmsMdBusinessCategory) {
        return bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryList(bmsMdBusinessCategory);
    }

    /**
     * 新增业务类别管理
     *
     * @param bmsMdBusinessCategory 业务类别管理
     * @return 结果
     */
    @Override
    public int insertBmsMdBusinessCategory(BmsMdBusinessCategory bmsMdBusinessCategory) {
        bmsMdBusinessCategory.setCreateTime(DateUtils.getNowDate());
        return bmsMdBusinessCategoryMapper.insertBmsMdBusinessCategory(bmsMdBusinessCategory);
    }

    /**
     * 修改业务类别管理
     *
     * @param bmsMdBusinessCategory 业务类别管理
     * @return 结果
     */
    @Override
    public int updateBmsMdBusinessCategory(BmsMdBusinessCategory bmsMdBusinessCategory) {
        bmsMdBusinessCategory.setUpdateTime(DateUtils.getNowDate());
        return bmsMdBusinessCategoryMapper.updateBmsMdBusinessCategory(bmsMdBusinessCategory);
    }

    /**
     * 批量删除业务类别管理
     *
     * @param ids 需要删除的业务类别管理ID
     * @return 结果
     */
    @Override
    public int deleteBmsMdBusinessCategoryByIds(String[] ids) {
        return bmsMdBusinessCategoryMapper.deleteBmsMdBusinessCategoryByIds(ids);
    }

    /**
     * 删除业务类别管理信息
     *
     * @param id 业务类别管理ID
     * @return 结果
     */
    @Override
    public int deleteBmsMdBusinessCategoryById(String id) {
        return bmsMdBusinessCategoryMapper.deleteBmsMdBusinessCategoryById(id);
    }

    @Override
    public List<TreeSelect> buildBusinessTreeSelect(List<BmsMdBusinessCategory> businessCategories) {
        List<BmsMdBusinessCategory> businessTrees = buildBusinessTree(businessCategories);
        return businessTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
        //return businessTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }
    
    @Override
    public List<TreeSelect> buildBusinessTreeSelectNew(List<BmsMdBusinessCategoryVO> businessCategories) {
        List<BmsMdBusinessCategoryVO> businessTrees = buildBusinessTreeNew(businessCategories);
        return businessTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
        //return businessTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }


    /**
     * 构建前端所需要下拉树结构
     *
     * @param businessCategorys 业务类别列表
     * @param filter            是否进行过滤
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelectAndChildrenNum> buildBusinessTreeSelectAndChildrenNum(List<BmsMdBusinessCategory> businessCategorys, Boolean filter) {
        List<BmsMdBusinessCategory> trees = buildBusinessTree(businessCategorys);
        //处理非叶子的子类数量
        for (Iterator<BmsMdBusinessCategory> it = trees.iterator(); it.hasNext(); ) {
            //Integer firstNum = 0;
            BmsMdBusinessCategory bmsMdBusinessCategory = it.next();
            //1级数量
            Integer firstNum = bmsMdBusinessCategory.getNum();

            if (CollectionUtils.isEmpty(bmsMdBusinessCategory.getChildren()) && filter) {
                //没有二级删除
                it.remove();
            } else {
                //通过第三级判断是否删除第一级
                Boolean del = true;
                //二级
                List<BmsMdBusinessCategory> childrenList = bmsMdBusinessCategory.getChildren();
                for (Iterator<BmsMdBusinessCategory> childrenIt = childrenList.iterator(); childrenIt.hasNext(); ) {
                    //Integer secondNum = 0;
                    BmsMdBusinessCategory children = childrenIt.next();
                    //2级数量
                    Integer secondNum = children.getNum();

                    List<BmsMdBusinessCategory> children2List = children.getChildren();
                    if (CollectionUtils.isEmpty(children2List) && filter) {
                        //没有三级删除
                        childrenIt.remove();

                    } else {
                        //有第三级的时候，置为false
                        if (del) {
                            del = false;
                        }
                        //三级
                        for (BmsMdBusinessCategory b : children2List) {
                            secondNum += b.getNum();
                        }
                        children.setNum(secondNum);
                    }
                    firstNum += secondNum;
                }
                //一级子节点,没有三级的情况，直接删除（
                if (del && filter) {
                    it.remove();
                } else {
                    bmsMdBusinessCategory.setNum(firstNum);
                }
            }
        }
        return trees.stream().map(TreeSelectAndChildrenNum::new).collect(Collectors.toList());
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<BmsMdBusinessCategory> list, BmsMdBusinessCategory t) {
        // 得到子节点列表
        List<BmsMdBusinessCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (BmsMdBusinessCategory tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                Iterator<BmsMdBusinessCategory> it = childList.iterator();
                while (it.hasNext()) {
                    BmsMdBusinessCategory n = (BmsMdBusinessCategory) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }
    
    /**
     * 递归列表
     */
    private void recursionFnNew(List<BmsMdBusinessCategoryVO> list, BmsMdBusinessCategoryVO t) {
        // 得到子节点列表
        List<BmsMdBusinessCategoryVO> childList = getChildListNew(list, t);
        t.setChildren(childList);
        for (BmsMdBusinessCategoryVO tChild : childList) {
            if (hasChildNew(list, tChild)) {
                // 判断是否有子节点
                Iterator<BmsMdBusinessCategoryVO> it = childList.iterator();
                while (it.hasNext()) {
                	BmsMdBusinessCategoryVO n = (BmsMdBusinessCategoryVO) it.next();
                    recursionFnNew(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<BmsMdBusinessCategory> getChildList(List<BmsMdBusinessCategory> list, BmsMdBusinessCategory t) {
        List<BmsMdBusinessCategory> tlist = new ArrayList<BmsMdBusinessCategory>();
        Iterator<BmsMdBusinessCategory> it = list.iterator();
        while (it.hasNext()) {
            BmsMdBusinessCategory n = (BmsMdBusinessCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && t.getGuid().equals(n.getParentId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }
    /**
     * 得到子节点列表
     */
    private List<BmsMdBusinessCategoryVO> getChildListNew(List<BmsMdBusinessCategoryVO> list, BmsMdBusinessCategoryVO t) {
        List<BmsMdBusinessCategoryVO> tlist = new ArrayList<BmsMdBusinessCategoryVO>();
        Iterator<BmsMdBusinessCategoryVO> it = list.iterator();
        while (it.hasNext()) {
        	BmsMdBusinessCategoryVO n = (BmsMdBusinessCategoryVO) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && t.getGuid().equals(n.getParentId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<BmsMdBusinessCategory> list, BmsMdBusinessCategory t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }
    
    /**
     * 判断是否有子节点
     */
    private boolean hasChildNew(List<BmsMdBusinessCategoryVO> list, BmsMdBusinessCategoryVO t) {
        return getChildListNew(list, t).size() > 0 ? true : false;
    }

    @Override
    public List<BmsMdBusinessCategory> buildBusinessTree(List<BmsMdBusinessCategory> businessCategories) {
        List<BmsMdBusinessCategory> returnList = new ArrayList<BmsMdBusinessCategory>();
        List<String> tempList = new ArrayList<String>();
        for (BmsMdBusinessCategory businessCategory : businessCategories) {
            tempList.add(businessCategory.getGuid());
        }
        for (Iterator<BmsMdBusinessCategory> iterator = businessCategories.iterator(); iterator.hasNext(); ) {
            BmsMdBusinessCategory businessType = (BmsMdBusinessCategory) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(businessType.getParentId())) {
                recursionFn(businessCategories, businessType);
                returnList.add(businessType);
            }
        }
        if (returnList.isEmpty()) {
            returnList = businessCategories;
        }
        return returnList;
    }
    
    @Override
    public List<BmsMdBusinessCategoryVO> buildBusinessTreeNew(List<BmsMdBusinessCategoryVO> businessCategories) {
        List<BmsMdBusinessCategoryVO> returnList = new ArrayList<BmsMdBusinessCategoryVO>();
        List<String> tempList = new ArrayList<String>();
        for (BmsMdBusinessCategoryVO businessCategory : businessCategories) {
            tempList.add(businessCategory.getGuid());
        }
        for (Iterator<BmsMdBusinessCategoryVO> iterator = businessCategories.iterator(); iterator.hasNext(); ) {
        	BmsMdBusinessCategoryVO businessType = (BmsMdBusinessCategoryVO) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(businessType.getParentId())) {
                recursionFnNew(businessCategories, businessType);
                returnList.add(businessType);
            }
        }
        if (returnList.isEmpty()) {
            returnList = businessCategories;
        }
        return returnList;
    }

    @Override
    public List<BmsMdBusinessCategory> selectBusinessCategoryAndChildrenNumList(BmsMdBusinessCategory bmsMdBusinessCategory, String tableName) {
        return bmsMdBusinessCategoryMapper.selectBusinessCategoryAndChildrenNumList(bmsMdBusinessCategory, tableName);
    }

    @Override
    public List<BmsMdBusinessCategory> selectBusinessCategorySelectOneToMore(BmsMdBusinessCategory businessCategory, String name) {
        return  bmsMdBusinessCategoryMapper.selectBusinessCategorySelectOneToMore(businessCategory,name);
    }
    /**
     * 构建前端所需要下拉树结构
     *
     * @param businessCategorys 业务类别列表
     * @param
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelectAndChildrenNum> buildBusinessTreeSelectAndChildrenNum(List<BmsMdBusinessCategory> businessCategorys) {
        List<BmsMdBusinessCategory> trees = buildBusinessTree(businessCategorys);
        //处理非叶子的子类数量
        for (Iterator<BmsMdBusinessCategory> it = trees.iterator(); it.hasNext(); ) {
            Integer firstNum = 0;
            BmsMdBusinessCategory bmsMdBusinessCategory = it.next();

            if (CollectionUtils.isEmpty(bmsMdBusinessCategory.getChildren())) {
                //没有二级删除
            } else {
                //通过第三级判断是否删除第一级
                Boolean del = true;
                //二级
                List<BmsMdBusinessCategory> childrenList = bmsMdBusinessCategory.getChildren();
                for (Iterator<BmsMdBusinessCategory> childrenIt = childrenList.iterator(); childrenIt.hasNext(); ) {
                    Integer secondNum = 0;
                    BmsMdBusinessCategory children = childrenIt.next();
                    List<BmsMdBusinessCategory> children2List = children.getChildren();
                    if (CollectionUtils.isEmpty(children2List) ) {
                        //没有三级删除
                        firstNum += children.getNum();
                    } else {
                        //有第三级的时候，置为false
                        if (del) {
                            del = false;
                        }
                        //三级
                        for (BmsMdBusinessCategory b : children2List) {
                            firstNum += b.getNum();
                            secondNum += b.getNum();
                        }
                        children.setNum(secondNum);
                    }

                }
                //一级子节点,没有三级的情况，直接删除（
                if (del) {

                } else {
                    bmsMdBusinessCategory.setNum(firstNum);
                }
                bmsMdBusinessCategory.setNum(firstNum);
            }
        }
        return trees.stream().map(TreeSelectAndChildrenNum::new).collect(Collectors.toList());
    }

	@Override
	public List<String> selectBusinessIds(String userId) {
		return bmsUserBusinessMapper.selectBusinessIds(userId);
	}

	@Override
	public List<TreeSelectAndChildrenNum> selectFunOptions() {
		return bmsMdBusinessCategoryMapper.selectFunOptions();
	}

    /**
     * 查询工程招标及工程招标子类
     * @return
     */
    @Override
    public Set<String> selectEngineeringBidding() {
        Set<String> sets = new HashSet<>();
        sets = this.selectGuidByParentId(Constants.BUSINESS_CATEGORY_NAME_ENGINEERING_BIDDING, null);
        for (String guid : sets) {
            Set<String> setTwo = this.selectGuidByParentId(null, guid);
            for (String guidTwo  : setTwo) {
                sets.addAll(this.selectGuidByParentId(null, guidTwo));
            }
            sets.addAll(setTwo);
        }
        return sets;
    }

    @Override
    public Set<String> selectGuidByParentId(String menuName, String parentId) {
        return bmsMdBusinessCategoryMapper.selectGuidByParentId(menuName, parentId);
    }

	@Override
	public Integer checkAgency(String businessTypeId) {
		return bmsMdBusinessCategoryMapper.checkAgency(businessTypeId);
	}

}
